package com.ai.platform.core.tag;

import org.apache.commons.lang3.StringUtils;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.engine.AttributeName;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractAttributeTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.templatemode.TemplateMode;

/**
 * @Auther: yeyingsheng
 * @Date: 2018/5/27 08:54
 * @Description:
 */
public class PermissionTagProcessor extends AbstractAttributeTagProcessor {

    private static final String ATTRIBUTE_NAME = "hasPermission";
    private static final int PRECEDENCE = 300;
    private static final String SPLIT="::";

    protected PermissionTagProcessor(String dialectPrefix) {
        super(
                TemplateMode.HTML, // This processor will apply only to HTML mode
                dialectPrefix, // Prefix to be applied to name for matching
                null, // No tag name: match any tag name
                false, // No prefix to be applied to tag name
                ATTRIBUTE_NAME, // Name of the attribute that will be matched
                true, // Apply dialect prefix to attribute name
                PRECEDENCE, // Precedence (inside dialect's precedence)
                true); // Remove the matched attribute afterwards
    }

    @Override
    protected void doProcess(ITemplateContext iTemplateContext, IProcessableElementTag iProcessableElementTag, AttributeName attributeName, String value, IElementTagStructureHandler iElementTagStructureHandler) {
        if(StringUtils.isNotBlank(value) && value.indexOf(SPLIT)!=-1){
            String[] values=value.split(SPLIT);
            String permission=values[0]+SPLIT+values[1];
            if(!ShiroFacade.hasAllPermissions(permission)){
                iElementTagStructureHandler.removeElement();
            }
        }
    }

}
